package com.jl.card.provider.jl3g;

import opencard.core.service.CardServiceInvalidParameterException;
import opencard.core.terminal.CommandAPDU;
import opencard.core.terminal.ResponseAPDU;

import com.jl.card.Card;
import com.jl.card.SWException;
import com.jl.card.file.CardFile;
import com.jl.card.file.CardFilePath;
import com.jl.card.filesystem.IFileSystem;
import com.jl.util.HexUtil;

import de.cardcontact.opencard.service.isocard.IsoConstants;

public class JL3GFileSystem implements IFileSystem {

	private Card card;

	// private APDUWrap wrap;

	public JL3GFileSystem(Card card) {
		this.card = card;
	}

	@Override
	public void create(String parent, byte[] data) throws SWException {

		CommandAPDU com = new CommandAPDU(261);
		ResponseAPDU res = new ResponseAPDU(2);

		if (data.length > 255) {
			throw new CardServiceInvalidParameterException(
					"create: length of data = " + data.length);
		}
		if (parent != null && parent.trim().length() != 0) {
			CardFile file = new CardFile(card, parent);
			file.select();
		}

		com.setLength(0);
		com.append(IsoConstants.CLA_ISO);
		com.append(IsoConstants.INS_CREATE_FILE);
		com.append((byte) 0x00);
		com.append((byte) 0x00);

		com.append((byte) data.length);
		System.arraycopy(data, 0, com.getBuffer(), 5, data.length);
		com.setLength(5 + data.length);
		res = card.sendCommandAPDU(com);
		if (res.sw() != IsoConstants.RC_OK) {
			throw new SWException(res.sw(), "CREATE_FILE");
		}
	}

	@Override
	public void delete(String filePath) throws SWException {

		CommandAPDU com = new CommandAPDU(261);
		ResponseAPDU res = new ResponseAPDU(2);

		byte[] data = new byte[2];
		CardFilePath path = new CardFilePath(filePath);
		if (path.getDeep() == 0) {
			throw new CardServiceInvalidParameterException(
					"file path foramt wrong");
		}
		short id = path.getID(path.getDeep() - 1);
		data[0] = HexUtil.highByte(id);
		data[1] = HexUtil.lowByte(id);
		com.setLength(0);
		com.append(IsoConstants.CLA_ISO);
		com.append(IsoConstants.INS_DELETE_FILE);
		com.append((byte) 0x00);
		com.append((byte) 0x00);
		com.append((byte) data.length);
		com.append(data);
		res = card.sendCommandAPDU(com);
		if (res.sw() != IsoConstants.RC_OK) {
			throw new SWException(res.sw(), "DELETE_FILE");
		}
	}

}
